import {messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import config from 'config'
import { message, Form, Switch, Icon, Row, Col, Button, Input, Radio, Select, Popover } from 'antd'
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
import 'styles/setting/sub-application/sub-application.scss'
import menuRoute from 'routes/menuRoute'
import { LanguageInput, ImageUpload } from 'components/index'
import debounce from 'lodash.debounce';
import ListSelector from "components/list-selector";
import subApplicationService from 'containers/setting/sub-application/sub-application.service'

class SubApplicationInfo extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      showSelectEmployeeGroup: false, //是否展示选择人员组
      chosenEmployeeIDs:[], //选中的人员组id
      employeeValue: 1001,
      uploadedImages: [],//已经上传的Logo
      subApplicationData: {
        appName: "",//名称
        appDesc: "",//描述
        i18n: {}//包含名称,描述
      },
      chosenEmployeeNames:[], //选中的人员组names
      subApplicationPage: menuRoute.getRouteItem('sub-application','key'),    //子应用管理的页面项
    };
    this.validateAppCode = debounce(this.validateAppCode, 1000);
  }

  componentDidMount() {
    let subApplicationID = this.props.params.id;
    if(subApplicationID) {
      this.getDetailInfo(subApplicationID);
    }
    if(window.location.href.indexOf("privatization") !== -1){
      this.setState({
        subApplicationPage: menuRoute.getRouteItem('sub-application-privatization','key'),//子应用管理私有化的页面项,
      })
    }
  }

  //获取子应用详情
  getDetailInfo = (subApplicationID)=>{
    const {chosenEmployeeNames} = this.state;
    subApplicationService.getSubApplication(subApplicationID, true).then(res => {
      if (res.status === 200){
        if(res.data.userGroupList && res.data.userGroupList.length){
          res.data.userGroupList.map(item => {
            chosenEmployeeNames.addIfNotExist(item.name)
          });
          this.setState({
            chosenEmployeeNames,
          })
        }
        this.initDetailData(res.data);
      }
    }).catch(error => {
      let errorMessage = messages('common.error');
      if (error.response && error.response.data && error.response.data.message) {
        errorMessage = error.response.data.message;
      }
    });
  };

  //初始化子应用详情页数据
  initDetailData = (data)=>{
    this.setState({
      subApplicationData: data
    });
    this.props.form.setFieldsValue({
      'appIcon': data.appIcon,
      'appName': data.appName,
      'appCode': data.appCode,
      'remark': data.appDesc,
      'platform': data.platform,
      'link': data.link,
      'nativeTitle': data.nativeTitle,
      'enableBadge': data.enableBadge,
      'enabled': data.enabled
    });
    let uploadedImage = [];
    let image = {};
    image.iconURL = data.appIcon;
    image.fileURL = data.appIcon;
    image.thumbnailUrl = data.appIcon;
    image.attachmentOID = 'Logo';
    image.fileName = 'Logo';
    uploadedImage.push(image);
    this.setState({
      uploadedImages: uploadedImage
    });
    if (data.showAll) {
      this.setState({
        employeeValue: 1001
      });
    } else if (!data.showAll && data.userGroupList && data.userGroupList.length) {
      let IDs = [];
      data.userGroupList.map(item => {
        let tempValue = {
          id: `${item.id}`,//防止id不是字符串类型，强制id转换为字符串类型
          name: `${item.name}` //防止id不是字符串类型，强制id转换为字符串类型
        };
        IDs.push(tempValue);
      });
      this.setState({
        employeeValue: 1002,
        chosenEmployeeIDs: IDs
      });
    }
  };

  //子应用名称：多语言
  i18nAppNameChange = (name, i18nName) => {
    const subApplicationData = this.state.subApplicationData;
    subApplicationData.appName = name;
    if (!subApplicationData.i18n) {
      subApplicationData.i18n = {};
    }
    subApplicationData.i18n.appName = i18nName;
  };

  //子应用描述：多语言
  i18nAppDescChange = (name, i18nName) => {
    const subApplicationData = this.state.subApplicationData;
    subApplicationData.appDesc = name;
    if (!subApplicationData.i18n) {
      subApplicationData.i18n = {};
    }
    subApplicationData.i18n.appDesc = i18nName;
  };

  handleSave = (e) => {
    e.preventDefault();
    let _subApplicationData = this.state.subApplicationData;
    let subApplicationID = this.props.params.id;
    //校验人员组的选择
    if (this.state.employeeValue === 1002 && !this.state.chosenEmployeeIDs.length) {
      message.error(messages('setting.key788'/*请选择人员组*/));//请选择人员组
    } else if (!this.state.uploadedImages.length) {
      message.error(messages('setting.key1027'/*请上传Logo*/));//请上传Logo
    } else {
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.setState({
            loading: true
          });
          _subApplicationData.appIcon = this.state.uploadedImages[0].fileURL;
          _subApplicationData.appCode = values.appCode;
          _subApplicationData.enabled = values.enabled;
          _subApplicationData.platform = values.platform;
          _subApplicationData.link = values.link;
          _subApplicationData.nativeTitle = values.nativeTitle;
          _subApplicationData.enableBadge = values.enableBadge;
          if (this.state.employeeValue === 1001) {
            _subApplicationData.showAll = true;
          } else {
            _subApplicationData.showAll = false;
            _subApplicationData.userGroupList = [];
            this.state.chosenEmployeeIDs.map(item => {
              _subApplicationData.userGroupList.push({id: item.id});
            });
          }
          if(subApplicationID) {
            this.updateSubApplication(_subApplicationData);
          } else {
            this.createSubApplication(_subApplicationData);
          }
        }
      });
    }
  };

  //编辑子应用
  updateSubApplication = (_subApplicationData) => {
    subApplicationService.updateSubApplication(_subApplicationData).then(resp => {
      this.setState({
        loading: false
      });
      if (resp.status === 200){
        this.context.router.replace(this.state.subApplicationPage.url);
      }
    }).catch(error => {
      this.setState({
        loading: false
      });
      let errorMessage = messages('common.error');
      if (error.response && error.response.data && error.response.data.message) {
        errorMessage = error.response.data.message;
      }
      message.error(errorMessage);
    });
  };

  //新建子应用
  createSubApplication = (_subApplicationData) => {
    subApplicationService.createSubApplication(_subApplicationData).then(resp => {
      this.setState({
        loading: false
      });
      if (resp.status === 200){
        this.context.router.replace(this.state.subApplicationPage.url);
      }
    }).catch(error => {
      this.setState({
        loading: false
      });
      let errorMessage = messages('common.error');
      if (error.response && error.response.data && error.response.data.message) {
        errorMessage = error.response.data.message;
      }
      message.error(errorMessage);
    });
  };

  //上传图片后的回调函数
  handleUploadImageChange = (fileList) => {
    if (!fileList || !fileList.length) {
      this.props.form.setFieldsValue({'appIcon': ''});
    } else {
      this.setState({uploadedImages: fileList});
    }
  };

  //改变人员组设置
  onChangeEmployeeValue = (e) => {
    this.setState({
      employeeValue: e.target.value
    }, () => {
      this.setState({chosenEmployeeIDs: []});
    });
  };

  //选择人员组
  handleShowGroupModal = () => {
    this.refs.chooserGroupBlur.focus();
    this.setState({showSelectEmployeeGroup: true});
  };

  handleSelectEmployeeCancel = () => {
    this.setState({showSelectEmployeeGroup: false})
  };

  handleSelectEmployeeOk = (values) => {
    let IDs = [];
    let Names = [];
    values.result.map(item => {
      IDs.push({id: item.id, name: item.name});
      Names.push(item.name);
    });
    this.setState({
      chosenEmployeeIDs: IDs,
      chosenEmployeeNames: Names,
    });
    this.handleSelectEmployeeCancel();
  };

  //校验appCode
  validateAppCode = (item,value,callback)=>{
    let subApplicationID = this.props.params.id;
    if (value) {
      subApplicationService.isValidAppCode(value, subApplicationID).then(resp => {
        if (resp.status === 200){
          callback();
        }
      }).catch(error => {
        let errorMessage = messages('common.error');
        if (error.response && error.response.data && error.response.data.message) {
          errorMessage = error.response.data.message;
        }
        callback(errorMessage);
      });
    } else {
      callback();
    }
  };

  render() {

    const { getFieldDecorator } = this.props.form;
    const { subApplicationPage, subApplicationData, showSelectEmployeeGroup, chosenEmployeeIDs, chosenEmployeeNames } = this.state;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 10, offset: 1 },
    };
    const noteContent = (
      <span>{messages('setting.key1789')/*新消息角标*/}&nbsp;
        <Popover content={<div style={{fontSize: 12, maxWidth: 200}}>{messages('setting.key1790')/*当该应用有新消息推送时，右上角显示红色数量角标*/}</div>}
                 trigger="hover">
              <span style={{color: 'gray'}}><Icon type="question-circle-o" /></span>
        </Popover>
      </span>
    );
    return (
      <div className="sub-application-info">
        <div>
          {!subApplicationData.id && (
            <span style={{fontSize: 18, fontWeight: 700, color: '#656565'}}>{messages('setting.key1028'/*新建应用*/)}</span>
          )}
          {subApplicationData.id && (
            <span style={{fontSize: 18, fontWeight: 700, color: '#656565'}}>{messages('setting.key1025'/*编辑应用*/)}</span>
          )}
        </div>
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('common.column.status')/* 状态 */}>
            {getFieldDecorator('enabled', {
              initialValue: true
            })(
              <Switch defaultChecked={true} checked={this.props.form.getFieldValue('enabled')} checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="cross" />}/>
            )}&nbsp;&nbsp;&nbsp;{this.props.form.getFieldValue('enabled') ? messages('common.status.enable') : messages('common.status.disable')}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1029'/*应用Logo*/)}>
            {getFieldDecorator("appIcon", {
              rules: [{
                required: true,
                message: messages('setting.key1027'/*请上传Logo*/) //请上传Logo
              }],
              initialValue: ''
            })(
              <div>
                <ImageUpload attachmentType="APPLICATION_ICON"
                             uploadUrl={`${config.baseUrl}/api/upload/static/attachment`}
                             fileType={['PNG', 'png', 'jpg', 'JPG', 'JPEG', 'jpeg']}
                             defaultFileList={this.state.uploadedImages}
                             onChange={this.handleUploadImageChange}
                             isShowDefault={true}
                             fileSize={.2}
                             maxNum={1}/>
                <div style={{color: '#999', fontSize: 12}}>{messages('setting.key1030'/*建议尺寸：150*150，200K以内的JPG.PNG图片*/)}</div>
              </div>
            )}
          </FormItem>
          {subApplicationData.id && (
            <FormItem {...formItemLayout} label='ID'>
              {getFieldDecorator('appID', {
                initialValue: subApplicationData.id
              })(
                <Input disabled={true} />
              )}
            </FormItem>
          )}
          <FormItem {...formItemLayout} label={messages('setting.key1026'/*应用名称*/)}>
            {getFieldDecorator('appName', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                },
                {
                  max: 20,
                  message: messages('common.max.characters.length', {max: 20})
                }
              ],
              initialValue: ''
            })(
              <LanguageInput
                key={1}
                name={subApplicationData.appName}
                i18nName={subApplicationData.i18n && subApplicationData.i18n.appName ? subApplicationData.i18n.appName : null}
                placeholder={messages('setting.key1467',{arg1: 20}/*请输入，最多输入{arg1}个字符*/)}
                isEdit={subApplicationData.id}
                nameChange={this.i18nAppNameChange}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='APP CODE'>
            {getFieldDecorator('appCode', {
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')  //请输入
                },
                {
                  max: 20,
                  message: messages('common.max.characters.length', {max: 20})
                },
                {
                  validator:(item,value,callback)=>this.validateAppCode(item,value,callback)
                }
              ],
              initialValue: ''
            })(
              <Input disabled={!!subApplicationData.id} placeholder={messages('setting.key1467',{arg1: 20}/*请输入，最多输入{arg1}个字符*/)}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1031'/*描述*/)}>
            {getFieldDecorator('remark', {
              rules: [
                {
                  max: 40,
                  message: messages('common.max.characters.length', {max: 40})
                }
              ],
              initialValue: ''
            })(
              <LanguageInput
                key={2}
                name={subApplicationData.appDesc}
                i18nName={subApplicationData.i18n && subApplicationData.i18n.appDesc ? subApplicationData.i18n.appDesc : null}
                placeholder={messages('setting.key1467',{arg1: 40}/*请输入，最多输入{arg1}个字符*/)}
                isEdit={subApplicationData.id}
                nameChange={this.i18nAppDescChange}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1032'/*跳转链接*/)}>
            {getFieldDecorator('link', {
              rules: [{
                required: true,
                message: messages('common.please.enter')  //请输入
              }],
              initialValue: ''
            })(
              <Input placeholder={messages('common.please.enter')/* 请输入 */}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1033'/*终端*/)}>
            {getFieldDecorator('platform', {
              initialValue: 'MOBILE'
            })(
              <RadioGroup>
                <Radio value='WEB'>Web</Radio>
                <Radio value='MOBILE'>{messages('setting.key1034'/*移动端（含APP/微信/钉钉）*/)}</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1791')/*顶部导航*/}>
            {getFieldDecorator('nativeTitle', {
              initialValue: false
            })(
              <RadioGroup>
                <Radio value={false}>{messages('setting.key1792')/*隐藏*/}</Radio>
                <Radio value={true}>{messages('setting.key1793')/*显示*/}</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={noteContent}>
            {getFieldDecorator('enableBadge', {
              initialValue: false
            })(
              <RadioGroup>
                <Radio value={false}>{messages('setting.key1792')/*隐藏*/}</Radio>
                <Radio value={true}>{messages('setting.key1793')/*显示*/}</Radio>
              </RadioGroup>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key1036'/*适用人员设置*/)}>
            <RadioGroup onChange={this.onChangeEmployeeValue} value={this.state.employeeValue}>
              <Radio key="generalduty" name="personArea"
                     value={1001}>{messages('setting.key1037'/*通用*/)}</Radio>
              <Radio key="selectFromStaffGroup" name="personArea"
                     value={1002}>{messages('setting.key1038'/*从人员组选择*/)}</Radio>
            </RadioGroup>
            {this.state.employeeValue === 1002 && (
              <div>
                <Select placeholder={chosenEmployeeIDs.length ? messages('setting.key1468',{arg1: chosenEmployeeIDs.length}/*已选择{arg1}个人员组*/) : messages('common.please.select')}
                        onFocus={this.handleShowGroupModal}
                        dropdownStyle={{display: 'none'}}/>
                <input ref="chooserGroupBlur" style={{position: 'absolute', top: '-9999vh', zIndex: -1}}/>
                <div style={{marginTop: 5}}>
                  {
                    chosenEmployeeNames.map((item, index) => {
                      return ( <span key={index}>{item}&nbsp;&nbsp;</span>)
                    })
                  }
                </div>
              </div>
            )}
          </FormItem>
          <FormItem wrapperCol={{ offset: 7 }}>
            <Row gutter={1}>
              <Col span={3}><Button type="primary" htmlType="submit" loading={this.state.loading}>{messages('common.save')/* 保存 */}</Button></Col>
              <Col span={3}><Button onClick={() => {this.context.router.replace(subApplicationPage.url);}}>{messages('common.back')/* 返回 */}</Button></Col>
            </Row>
          </FormItem>
        </Form>
        <ListSelector type="user_group"
                      selectedData={chosenEmployeeIDs}
                      labelKey="name"
                      showDetail={true}
                      visible={showSelectEmployeeGroup}
                      onOk={this.handleSelectEmployeeOk}
                      onCancel={this.handleSelectEmployeeCancel}/>
      </div>
    )
  }
}

SubApplicationInfo.contextTypes ={
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language
  }
}

const WrappedSubApplicationInfo = Form.create()(SubApplicationInfo);

export default connect(mapStateToProps)(WrappedSubApplicationInfo)
